//
//  BLBaseListViewDataController.m
//  BasketBallLeagues
//
//  Created by kenshin on 4/27/17.
//  Copyright © 2017 kenshin. All rights reserved.
//

#import "BLBaseListViewDataController.h"
#import "BLApi.h"

@interface BLBaseListViewDataController ()

@property (nonatomic, strong, readwrite) TKBasePageRequest *request;

@property (nonatomic) Class decodeClass;
@property (nonatomic, copy) BLBaseListViewDataAfterParseCompletionBlock afterParseCompletion;

@end

@implementation BLBaseListViewDataController

- (instancetype)initWithRequest:(TKBasePageRequest *)request decodeClass:(Class)decodeClass afterParseCompletion:(BLBaseListViewDataAfterParseCompletionBlock)afterParseCompletion {
    if(self = [self init]) {
        _request = request;
        _decodeClass = decodeClass;
        _afterParseCompletion = afterParseCompletion;
    }
    
    return self;
}

- (void)startRequestCompletion:(void(^)(NSArray *, NSError *))completion
{
    NSAssert([self.decodeClass isSubclassOfClass:[TKBasePageResponse class]], @"decodeClass必须为TKBasePageResponse的子类");
    
    @weakify(self);
    [BLApi startRequest:self.request decodeClass:self.decodeClass completion:^(id responseObject, id jsonObject, NSError *error) {
        @strongify(self);
        if (!error) {
            if (self.afterParseCompletion) {
                KSAsyncRun(^{
                    if ([(TKBasePageResponse *)responseObject page_flag] > 0) {
                        self.request.page_flag = [(TKBasePageResponse *)responseObject page_flag];
                    }
                    
                    self.afterParseCompletion(responseObject);
                    KSAsyncRunInMain(^{
                        if (completion) {
                            completion([(TKBasePageResponse *)responseObject items], error);
                        }
                    });
                });
            } else {
                if (completion) {
                    completion([(TKBasePageResponse *)responseObject items], error);
                }
            }
            return;
        }
        if (completion) {
            completion(nil, error);
        }
    }];
}

- (void)stopRequest
{
    [self.request stopRequest];
}

- (void)setCurrentPage:(NSUInteger)currentPage
{
    self.request.page = currentPage+1; //+1是因为服务器第一页是1而不是0
}

- (NSInteger)minItemCountOfTryToLoadMoreData {
    return minItemCount;
}

@end
